package com.itheima.health.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class UserServiceSecurity implements UserDetailsService {

    @Reference
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User pojouser =userService.findUserByUsername(username);
        ArrayList<GrantedAuthority> list = new ArrayList<>();
        if(pojouser!=null&&pojouser.getRoles()!=null&&pojouser.getRoles().size()>0){
            for (Role role : pojouser.getRoles()) {
                if(role!=null&&role.getPermissions()!=null&&role.getPermissions().size()>0){
                    for (Permission permission : role.getPermissions()) {
                        String keyword = permission.getKeyword();
                        list.add(new SimpleGrantedAuthority(keyword));
                    }
                }
            }
        }
        UserDetails user=new org.springframework.security.core.userdetails.User(username,pojouser.getPassword(),list);

        return user;
    }
}
